<template>
    <div>
        <div class="operation-container">
            <!--按钮区域  -->
            <div class="btn-area">
                <el-button type="primary" @click="handleAdd">新增</el-button>
                <el-button type="warning" @click="handleExpand">展开/折叠</el-button>
            </div>

            <!-- 搜索区域 -->
            <div class="search-area">
                <el-form :inline="true">
                    <el-form-item >
                        <el-input v-model="queryParams.deptName" placeholder="部门名称" clearable></el-input>
                    </el-form-item>
                    <el-form-item >
                        <el-select v-model="queryParams.status" placeholder="部门状态" clearable class="status-select">
                            <el-option label="正常" value="0"></el-option>
                            <el-option label="停用" value="1"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="handleQuery">搜索</el-button>
                        <el-button @click="resetQuery">重置</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </div>



        <!-- 表格区域 -->
        <el-table ref="deptTable" :data="deptList" v-bind="tableProps" @resize-change="handleTableResize">
            <el-table-column prop="deptName" label="部门名称" width="180"></el-table-column>
            <el-table-column prop="orderNum" label="排序" width="80"></el-table-column>
            <el-table-column prop="leader" label="负责人"></el-table-column>
            <el-table-column prop="phone" label="联系电话"></el-table-column>
            <el-table-column prop="email" label="邮箱"></el-table-column>
            <el-table-column prop="status" label="状态" width="100">
                <template #default="scope">
                    <el-tag :type="scope.row.status === '0' ? 'success' : 'danger'">
                        {{ scope.row.status === '0' ? '正常' : '停用' }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间" width="180">
                <template #default="scope">
                    {{ scope.row.createTime }}
                </template>
            </el-table-column>
            <el-table-column label="操作" width="180">
                <template #default="scope">
                    <el-button type="text" @click="handleEdit(scope.row)">编辑</el-button>
                    <el-button type="text" @click="handleAdd(scope.row)">新增</el-button>
                    <el-button type="text" @click="handleDelete(scope.row)" v-if="scope.row.deptId !== 100"
                        style="color: #F56C6C">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
    </div>
    <el-dialog v-model="dialogVisible" :title="deptForm.deptId ? '编辑部门' : '新增部门'" width="600px"
        :close-on-click-modal="false" destroy-on-close>
        <el-form ref="deptForm" :model="deptForm" :rules="rules" label-width="100px" class="dept-form">
            <el-row :gutter="20">
                <el-col :span="24">
                    <el-form-item v-if="deptForm.deptId !== 100" label="上级部门" prop="parentId" required>
                        <el-tree-select v-model="deptForm.parentId" :data="deptList"
                            :props="{ label: 'deptName', value: 'deptId' }" placeholder="请选择上级部门" check-strictly
                            class="w-full" />
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="部门名称" prop="deptName" required>
                        <el-input v-model="deptForm.deptName" placeholder="请输入部门名称" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="显示排序" prop="orderNum" required>
                        <el-input-number v-model="deptForm.orderNum" :min="0" :max="999" controls-position="right"
                            class="w-full" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="部门状态" prop="status">
                        <el-radio-group v-model="deptForm.status">
                            <el-radio label="0">正常</el-radio>
                            <el-radio label="1">停用</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="负责人" prop="leader">
                        <el-input v-model="deptForm.leader" placeholder="请输入负责人" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="联系电话" prop="phone">
                        <el-input v-model="deptForm.phone" placeholder="请输入联系电话" />
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="邮箱" prop="email">
                        <el-input v-model="deptForm.email" placeholder="请输入邮箱" />
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitForm">确 定</el-button>
            </span>
        </template>
    </el-dialog>
</template>


<script>
import { getDeptList, addDept, updateDept, deleteDept } from '@/api/system/dept'

export default {
    name: 'SystemDept',
    data() {
        return {
            deptForm: {
                deptId: undefined,
                deptName: '',
                parentId: '',
                orderNum: '',
                leader: '',
                phone: '',
                email: '',
                status: '0'
            },
            dialogVisible: false,
            deptList: [],
            queryParams: {
                deptName: '',
                status: ''
            },
            rules: {
                parentId: [
                    { required: true, message: '请选择上级部门', trigger: 'change' }
                ],
                deptName: [
                    { required: true, message: '请输入部门名称', trigger: 'blur' }
                ],
                orderNum: [
                    { required: true, message: '请输入显示排序', trigger: 'blur' }
                ]
            },
            tableProps: {
                maxHeight: 'calc(100vh - 200px)',
                fit: true,
                border: true,
                rowKey: 'deptId',
                defaultExpandAll: true,
                treeProps: { children: 'children', hasChildren: 'hasChildren' }
            },
            isExpanded: true,
        }
    },
    mounted() {
        this.initTableHeight();
        this.handleResize = this.debounce(this.initTableHeight, 200);
        window.addEventListener('resize', this.handleResize);
    },
    beforeUnmount() {
        window.removeEventListener('resize', this.handleResize);
    },
    methods: {
        handleExpand() {
            this.isExpanded = !this.isExpanded;
            const table = this.$refs.deptTable;
            if (table) {
                // 获取所有数据
                const expandRows = (data) => {
                    data.forEach(row => {
                        table.toggleRowExpansion(row, this.isExpanded);
                        if (row.children && row.children.length) {
                            expandRows(row.children);
                        }
                    });
                };
                expandRows(this.deptList);
            }
        },

        initTableHeight() {
            this.$nextTick(() => {
                if (this.$refs.deptTable) {
                    // 使用 RAF 确保在下一帧执行
                    requestAnimationFrame(() => {
                        this.$refs.deptTable.doLayout();
                    });
                }
            });
        },
        handleTableResize() {
            this.debounce(() => {
                if (this.$refs.deptTable) {
                    requestAnimationFrame(() => {
                        this.$refs.deptTable.doLayout();
                    });
                }
            }, 100)();
        },
        handleAdd(row) {
            this.dialogVisible = true
            this.deptForm = {
                deptId: undefined,
                parentId: row ? row.deptId : '',
                deptName: '',
                orderNum: 0,
                leader: '',
                phone: '',
                email: '',
                status: '0'
            }
        },
        handleQuery() {
            console.log(this.queryParams)
            this.getDeptList()
        },
        resetQuery() {
            this.queryParams = {
                deptName: '',
                status: ''
            }
            this.getDeptList()
        },
        getDeptList() {
            // 获取部门列表
            getDeptList(this.queryParams).then(res => {
                this.deptList = res.data.data
                console.log(res)
            }).catch(err => {
                console.error('获取部门列表失败:', err)
            })
        },
        handleEdit(row) {
            this.dialogVisible = true
            this.deptForm = {
                ...row,
                status: row.status || '0'
            }
        },
        submitForm() {
            this.$refs.deptForm.validate(valid => {
                if (valid) {
                    const api = this.deptForm.deptId ? updateDept : addDept
                    api(this.deptForm).then(res => {
                        if (res.data.code === 200) {
                            this.$message.success(this.deptForm.deptId ? '修改成功' : '新增成功')
                            this.dialogVisible = false
                            this.getDeptList()
                        } else {
                            this.$message.error(res.data.message)
                        }
                    }).catch(err => {
                        console.error(this.deptForm.deptId ? '修改失败:' : '新增失败:', err)
                    })
                }
            })
        },
        handleDelete(row) {
            this.$confirm('是否确认删除部门【' + row.deptName + '】', '警告', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                // 修改API调用方式
                deleteDept(row.deptId).then(res => {
                    if (res.data.code === 200) {
                        this.$message.success('删除成功')
                        this.getDeptList()
                    } else {
                        this.$message.error(res.data.message)
                    }
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                })
            })
        },
        debounce(fn, delay) {
            let timer = null;
            return function (...args) {
                if (timer) clearTimeout(timer);
                timer = setTimeout(() => {
                    fn.apply(this, args);
                }, delay);
            };
        },
    },
    created() {
        this.getDeptList()
    }
}
</script>
<style scoped>
.operation-container {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 8px;
}

.btn-area {
    display: flex;
    gap: 0;
}

/* 覆盖 Element Plus 按钮的默��外边距 */
.btn-area :deep(.el-button) {
    margin-left: 0;
    margin-right: 8px;
    /* 如果需要间距可以调整这个值 */
}

.btn-area :deep(.el-button:last-child) {
    margin-right: 0;
    /* 最后一个按钮不需要右边距 */
}

.search-area {
    display: flex;
    justify-content: flex-end;
}

/* 移除表单项的下边距 */
:deep(.el-form-item) {
    margin-bottom: 0;
}

/* 设置下拉框的宽度 */
:deep(.status-select) {
    width: 150px;
    /* 可以根据需要调整宽度 */
}

/* 新增部门表单样式 */
.dept-form {
    padding: 20px 10px;
}

.dept-form :deep(.el-form-item) {
    margin-bottom: 20px;
}

:deep(.w-full) {
    width: 100%;
}

:deep(.el-dialog__body) {
    padding: 10px 20px;
}

:deep(.dialog-footer) {
    padding: 0 20px 20px;
}

:deep(.el-form-item__label) {
    font-weight: 500;
}

/* 添加表格容器样式 */
.el-table {
    height: 100%;
    overflow: hidden;
    transition: none !important;
    /* 禁用过渡动画可能会有帮助 */
}

:deep(.el-table__body-wrapper) {
    overflow-y: auto;
    overflow-x: hidden;
    height: calc(100% - 40px);
    /* 减去表头高度 */
}

:deep(.el-table--scrollable-y) {
    height: 100%;
}

:deep(.el-table__inner-wrapper) {
    height: 100%;
}
</style>
